package com.atguigu.srb.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import java.time.Duration;

/**
 * ClassName: redisConfig
 * Package: com.atguigu.srb.core.config
 * Description:
 *
 * @Author 刘强
 * @Create 2024/4/18 16:35
 * @Version 1.0
 */
@Configuration
@EnableCaching  // 1. 开启缓存管理
public class redisConfig {
    //  组件的定制化-->@PostConstruct 对组件进行初始化设置(修改属性)  --> @PostConstruct
    @Autowired
    RedisTemplate redisTemplate;
    // 方式一：
    @PostConstruct
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    // 2. 创建缓存管理器为组件
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory){

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(60))
//                .disableCachingNullValues(); // 禁止缓存空数据
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer())) //key的序列化工具
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));// value的序列化工具

        RedisCacheManager cacheManager = RedisCacheManager
                .builder(lettuceConnectionFactory)  // redis的连接工厂
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}
